package cn.dansj.gateway.configure;

import cn.dansj.gateway.enums.GlobalEnv;
import cn.dansj.gateway.utils.RequestUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class FilterConfigure implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RequestUtils.setServerWebExchange(exchange);
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }

        if (GlobalEnv.innerPage.contains(exchange.getRequest().getURI().getPath())) {
            return RequestUtils.response("Page Not Found", 404);
        }

        Mono<Void> mono = chain.filter(exchange.mutate().request(exchange.getRequest().mutate().header("x-gateway-dispatch", "true").build()).build());
        RequestUtils.removeServerWebExchange();
        return mono;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
